# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import tools
from openerp import SUPERUSER_ID
import datetime,time
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _

ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = '%Y-%m-%d %H:%M:%S'


AVAILABLE_PRIORITIES = [
    ('0', 'Very Low'),
    ('1', 'Low'),
    ('2', 'Normal'),
    ('3', 'High'),
    ('4', 'Very High'),
]



class crm_phonecall(osv.osv):
    _inherit = "crm.phonecall"
    _order = "date desc"

    def create(self, cr, uid, vals, context=None):
        if not (vals.get('partner_id') or vals.get('opportunity_id')):
            raise osv.except_osv(u'错误', u"客户和线索字段必须填写一个，否组不能保存！")
        crm_phonecall_id = super(crm_phonecall, self).create(
            cr, uid, vals, context=context)
        if context.get("default_previous_contact_id"):
            self.write(cr, uid, crm_phonecall_id, {'previous_contact_id': context.get(
                "default_previous_contact_id")}, context=context)
        crm_phonecall_objs = self.browse(cr, uid, crm_phonecall_id, context=context)
        if vals.get('partner_id'):
            self.pool.get('res.partner').write(cr, uid, vals.get('partner_id'), {
                'last_contact_date': crm_phonecall_objs.create_date}, context=context)
        if vals.get('opportunity_id'):
            self.pool.get('crm.lead').write(cr, uid, vals.get('opportunity_id'), {
                'last_contact_date': crm_phonecall_objs.create_date}, context=context)
        return crm_phonecall_id

    def on_change_partner_id(self, cr, uid, ids, partner_id, context=None):
        # 495 东方团购客户的联系记录新建时，如果此客户有默认联系人，那么需要设置联系记录的默认联系人
        returns = super(crm_phonecall, self).on_change_partner_id(cr, uid, ids, partner_id, context=context)
        if partner_id or context.get("default_partner_id"):
            main_contacts = ""
            if not partner_id:
                partner = self.pool.get('res.partner').browse(cr, uid, context.get("default_partner_id"), context=context)
            else:
                partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
            if partner.main_contacts:
                main_contacts = partner.main_contacts
            # if partner.multi_address_ids:
            #     contacts_name = partner.multi_address_ids[0].id
            returns.update({'value':
                            {'contacts_people': main_contacts, 'contacts_name': partner.name}})
            returns.update({'domain':
                            {'contacts_people': [('id', 'in', [contact_childs.id for contact_childs in partner.child_contacts_ids])]}})
        else:
            returns.get('value').update(
                {'contacts_people': '', 'contacts_name': ''})
            returns.update({'domain': {'contacts_people': []}})
        return returns

    def onchange_contacts_people(self, cr, uid, ids, contacts_name_id, context=None):
        res = {}
        if contacts_name_id:
            contacts_people = self.pool.get("company.contacts").browse(cr, uid, contacts_name_id, context=context)
            res.update({'value': {'department': contacts_people.department, 'street': contacts_people.street, 'duties': contacts_people.position,
                                  'partner_mobile': contacts_people.mobile, 'partner_phone': contacts_people.phone, 'contacts_name': contacts_people.contacts_id.name}})
        else:
            res.update({'value': {'department': '', 'street': '', 'duties': '', 'partner_mobile': '', 'partner_phone': '', 'contacts_name': ''}})
        return res
    _columns = {
        'contacts_people': fields.many2one('company.contacts', u'联系人'),
        # previous
        'previous_contact_id': fields.many2one('crm.phonecall', string='上次联系记录'),
        'previous_contact_description': fields.text(string='上次联系记录明细'),
        'duties': fields.char(u'职务'),
        'department': fields.char(string="部门", size=None),
        'street': fields.char(u'地址'),
        'contact_type': fields.selection([(u'我方联系', u'我方联系'), (u'对方联系', u'对方联系'), (u'日常记录', u'日常记录')], string='联系类型'),
        'contact_result_type': fields.selection([(u'无效果', u'无效果'), (u'一般效果', u'一般效果'), (u'待跟进', u'待跟进'),
                                                 (u'意向定单', u'意向定单'), (u'近期拜访', u'近期拜访'), (u'今日拜访', u'今日拜访'),
                                                 (u'已成交', u'已成交')], string='联系结果类型'),
        'contacts_name': fields.char(string='联系人姓名'),
    }
    # _default = {
    #     'categ_id': lambda s, c, uid, ctx={}: s.pool.get("crm.case.categ").search(c, uid, [('name', '=', "我方去电")], context=ctx)[0]
    # }

    def default_get(self, cr, uid, fields, context=None):
        res = super(crm_phonecall, self).default_get(
            cr, uid, fields, context=context)
        if context.get('default_previous_contact_id'):
            crm_phonecall_obj = self.browse(cr, uid, context.get(
                'default_previous_contact_id'), context=context)[0]
            res.update(
                {'previous_contact_description': crm_phonecall_obj.description, 'partner_id': crm_phonecall_obj.partner_id.id})
        cr.execute("SELECT id FROM crm_case_categ WHERE name='Outbound'")
        crm_case_categ_row = cr.dictfetchone()
        res.update({'categ_id': crm_case_categ_row.get('id')})
        return res


class crm_lead(osv.osv):
    _name = "crm.lead"
    _inherit = ['china.city.county', 'crm.lead']

    # 建立联系人就职记录
    def create_customer_contacts(self, cr, uid, lead, parent_id, context=None):
        partner_pool = self.pool.get('res.partner')
        contacts_pool = self.pool.get('company.contacts')
        partner_value = {
            'parent_id': parent_id,
            'name': lead.contact_name,
            'is_company': False,
            'customer': False,
            'supplier': False,
            'contacts': True,  # 是联系人
            'phone': lead.phone,
            'mobile': lead.mobile,
            'fax': lead.fax,
            'zip': lead.zip,
            'email': lead.email_from,
            'province_id': lead.province_id and lead.province_id.id or False,
            'city_id': lead.city_id and lead.city_id.id or False,
            'county_id': lead.county_id and lead.county_id.id or False,
            'street': lead.street,
            'QQ': lead.QQ,
            'comment': lead.description,
            'user_id': lead.user_id and lead.user_id.id or False,
            'birthday': lead.birthday or False,
            'gender': lead.gender or False,
        }
        partner_id = partner_pool.create(cr, uid, partner_value, context=context)

        contact_value = {
            'partner_id': parent_id,  # 所属企业客户partner_id
            'contacts_id': partner_id,
            'position': lead.function,
            'department': lead.department,
            'is_inauguratory': True,
            'is_main_contacts': True,
            'mobile': lead.mobile,
            'email': lead.email_from

        }
        contacts_pool.create(cr, uid, contact_value, context=context)

    # 重载建立客户或联系人partner函数
    def _lead_create_contact(self, cr, uid, lead, name, is_company, parent_id=False, context=None):
        partner = self.pool.get('res.partner')
        vals = {'name': name,
                'user_id': lead.user_id and lead.user_id.id or False,
                'comment': lead.description,
                'section_id': lead.section_id and lead.section_id.id or False,
                'parent_id': parent_id,
                'phone': lead.phone,
                'mobile': lead.mobile,
                'email': tools.email_split(lead.email_from) and tools.email_split(lead.email_from)[0] or False,
                'fax': lead.fax,
                'title': lead.title and lead.title.id or False,
                'function': lead.function,  # 职务
                #'country_id': lead.country_id and lead.country_id.id or False,
                'province_id': lead.province_id and lead.province_id.id or False,
                'city_id': lead.city_id and lead.city_id.id or False,
                'county_id': lead.county_id and lead.county_id.id or False,
                'street': lead.street,
                #'street2': lead.street2,
                'zip': lead.zip,
                'state_id': lead.state_id and lead.state_id.id or False,
                'is_company': is_company,
                'type': 'contact',
                'cust_code': lead.cust_code,
                'last_contact_date': lead.last_contact_date,
                'department': lead.department,
                }
        return partner.create(cr, uid, vals, context=context)

    # 重载线索转客户函数
    def _create_lead_partner(self, cr, uid, lead, context=None):
        partner_id = False
        # 如果线索中存在联系人名称，直接调用_create_lead_partner不合适
        #partner_id = super(crm_lead, self)._create_lead_partner(cr, uid, lead, context=context)
        if lead.partner_name and lead.contact_name:
            # 建立企业客户partner记录
            partner_id = self._lead_create_contact(cr, uid, lead, lead.partner_name, True, context=context)
            # 建立联系人partner记录和就职记录company.contacrs
            self.create_customer_contacts(cr, uid, lead, partner_id, context=context)
            # 将线索的联系记录关联到新建的客户
            cr.execute("UPDATE crm_phonecall SET partner_id=%s WHERE opportunity_id=%s" % (partner_id, lead.id))
        else:
            raise osv.except_osv(
                _('Warning!'),
                _('No customer name defined. Please fill one of the following fields: Company Name, Contact Name or Email ("Name <email@address>")')
            )
        return partner_id

    def create(self, cr, uid, vals, context=None):
        model_data_obj = self.pool.get('ir.model.data')
        crm_stage_lead1_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead1')
        crm_stage_confirm_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead3')
        crm_stage_lead4_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead4')
        crm_stage_lead5_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead5')
        # 回到新建或者销售确认状态,清除采购确认时间,并且重置确认时间(需要检查权限,防止采购重置确认时间)
        if context.get('default_stage_id') and context.get('default_stage_id') == crm_stage_lead1_state_id:
            # 清除采购反馈时间
            vals.update({'confirm_date': None, 'feedback_date': None})
        if context.get('default_stage_id') and context.get('default_stage_id') == crm_stage_confirm_state_id:
            # 重置确认时间,清除采购反馈时间
            vals.update({'confirm_date': datetime.datetime.now(), 'feedback_date': None})
        if context.get('default_stage_id') and (context.get('default_stage_id') == crm_stage_lead4_state_id or vals.get(
                'default_stage_id') == crm_stage_lead5_state_id):
            vals.update({'feedback_date': datetime.datetime.now(), 'purchase_uid': uid})
        #vals.update({'last_contact_date': (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')}) #新建的时候不需要更新最后跟进时间
        return_vals = super(crm_lead, self).create(cr, uid, vals, context=context)
        return return_vals

    def continue_to_follow_up(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'last_contact_date':
                                      (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')}, context=context)
        return True

    def case_mark_lose(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'last_contact_date': (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')}, context=context)
        return super(crm_make_sale, self).case_mark_lose(cr, uid, ids, context=context)

    def write(self, cr, uid, ids, vals, context=None):
        model_data_obj = self.pool.get('ir.model.data')
        crm_stage_lead1_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead1')
        crm_stage_confirm_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead3')
        crm_stage_lead4_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead4')
        crm_stage_lead5_state_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'crm.stage_lead5')

        stage_id = vals.get('stage_id')
        #回到新建或者销售确认状态,清除采购确认时间,并且重置确认时间(需要检查权限,防止采购重置确认时间)
        if stage_id and stage_id == crm_stage_lead1_state_id:
            if uid != SUPERUSER_ID and self.pool.get('res.users').user_has_groups(cr, uid, groups='purchase.group_purchase_user', context=context):
                raise osv.except_osv(u'错误', u'您无法将此商机变为已草稿状态!')
            #清除采购反馈时间
            vals.update({'confirm_date': None, 'feedback_date': None,
                         'last_contact_date': (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')})

        if stage_id and stage_id == crm_stage_confirm_state_id:
            if uid != SUPERUSER_ID and self.pool.get('res.users').user_has_groups(cr, uid, groups='purchase.group_purchase_user', context=context):
                raise osv.except_osv(u'错误', u'您无法将此商机变为已销售确认状态!')
            #重置确认时间,清除采购反馈时间
            vals.update({'confirm_date': datetime.datetime.now(), 'feedback_date': None,
                         'last_contact_date': (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
                         })

        if stage_id and (stage_id == crm_stage_lead4_state_id or stage_id == crm_stage_lead5_state_id):
            crm_lead_row = self.browse(cr, uid, ids, context=context)
            #检查是否有采购权限
            if not self.pool.get('res.users').user_has_groups(cr, uid, groups='purchase.group_purchase_user', context=context):
                raise osv.except_osv(u'错误', u'您没有采购权限, 无法将此商机变为已采购反馈状态!')
            #检查是否有确认时间
            if not crm_lead_row.confirm_date:
                raise osv.except_osv(u'错误', u'销售还未确认, 无法将此商机进行反馈!')
            #如果拒绝,需要检查拒绝理由
            # if stage_id == crm_stage_lead4_state_id:
            #     if not crm_lead_row.refuse_reason:
            #         raise osv.except_osv(u'错误', u'还没有填写拒绝理由, 无法将商机状态变更为拒绝!')
            #写入采购反馈时间
            vals.update({'feedback_date': datetime.datetime.now(), 'purchase_uid': uid,
                         'last_contact_date': (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
                         })
        res = super(crm_lead, self).write(cr, uid, ids, vals, context=context)
        #商机采购通过后还是允许销售修改商机(暂时)
        # for crm_lead_row in self.browse(cr, uid, ids, context=context):
        #     if vals.get('crm_lead_line_ids') and (crm_lead_row.stage_id.id == crm_stage_lead4_state_id
        #                                           or crm_lead_row.stage_id.id == crm_stage_lead5_state_id
        #                                           or crm_lead_row.stage_id.id == crm_stage_confirm_state_id):
        #         raise osv.except_osv(u'错误', u'目前状态不能进行修改 商机产品列表!')
        return res

    def _set_feedback_time(self, cr, uid, ids, args, name, context=None):
        res = {}
        for id in ids:
            res[id] = {'feedback_time_diff': 0, 'feedback_time_diff_display': ''}
        for crm_lead_row in self.browse(cr, uid, ids, context=context):
            if crm_lead_row.confirm_date and crm_lead_row.feedback_date:
                confirm_date = time.mktime(time.strptime(crm_lead_row.confirm_date, '%Y-%m-%d %H:%M:%S'))
                feedback_date = time.mktime(time.strptime(crm_lead_row.feedback_date, '%Y-%m-%d %H:%M:%S'))
                feedback_seconds = feedback_date - confirm_date
                res[crm_lead_row.id]['feedback_time_diff'] = feedback_seconds
                feedback_minute = int(feedback_seconds / 3600)
                display_str = "%s小时%s分钟" % (
                feedback_minute, int((feedback_seconds % 3600) / 60)) if feedback_minute > 0 else "%s分钟" % (int((feedback_seconds % 3600) / 60))
                res[crm_lead_row.id]['feedback_time_diff_display'] = display_str
        return res

    def _compute_amount_total(self, cr, uid, ids, name, args, context=None):
        res = {}
        for lead_row in self.browse(cr, uid, ids, context=context):
            res[lead_row.id] = sum([line.product_uom_qty*line.price_unit for line in lead_row.crm_lead_line_ids]) or 0
        return res

    def _get_crm_lead_line_change(self, cr, uid, ids, context=None):
        res = []
        for line in self.browse(cr, uid, ids, context=context):
            res.append(line.crm_lead_id.id)
        return res

    _columns = {
        'last_contact_date': fields.datetime(u'最后跟进时间'),
        'crm_phonecall_ids': fields.one2many('crm.phonecall', 'opportunity_id', string=u'联系记录'),
        'cust_code': fields.char(u'客户编号'),
        'department': fields.char(u'部门'),
        'QQ': fields.char('QQ'),
        'birthday': fields.date(u'生日'),
        'gender': fields.selection([(u'男', u'男'), (u'女', u'女')], string=u'性别'),
        'is_subscription': fields.boolean(u'是否邮寄'),
        'confirm_date': fields.datetime(u'确认状态时间'),
        'feedback_date': fields.datetime(u'建议状态时间'),
        'order_id': fields.many2one('sale.order', u'报价单'),
        'feedback_time_diff': fields.function(_set_feedback_time, type='float', multi='feedback_time_diff',string=u'反馈时间差',
                    store={'crm.lead': (lambda self, cr, uid, ids, c={}: ids, ['confirm_date', 'feedback_date'],10)}),
        'feedback_time_diff_display': fields.function(_set_feedback_time, type='char', multi='feedback_time_diff_display',string=u'反馈时间差',
                    store={'crm.lead': (lambda self, cr, uid, ids, c={}: ids, ['confirm_date', 'feedback_date'], 10)}),
        'crm_lead_line_ids':fields.one2many('crm.lead.line','crm_lead_id',string='商机产品列表'),
        'refuse_reason': fields.char(u'采购回复'),
        'priority': fields.selection(AVAILABLE_PRIORITIES, 'Priority', select=True, track_visibility='onchange'),
        'purchase_uid': fields.many2one('res.users', u'采购员'),
        'amount_total': fields.function(_compute_amount_total, string=u'总金额', type='float', store={
            'crm.lead.line':(_get_crm_lead_line_change, ['product_id', 'price_subtotal', 'price_unit', 'product_uom_qty'], 10),
            'crm.lead': (lambda self, cr, uid, ids, c={}: ids, ['crm_lead_line_ids'], 10),
        }),
    }

    # 客户变更,需要改变销售员
    def on_change_partner_id(self, cr, uid, ids, partner_id, context=None):
        values = {}
        if partner_id:
            partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
            partner_name = (partner.parent_id and partner.parent_id.name) or (partner.is_company and partner.name) or False
            values = {
                'partner_name': partner_name,
                'contact_name': (not partner.is_company and partner.name) or False,
                'title': partner.title and partner.title.id or False,
                'street': partner.street,
                'street2': partner.street2,
                'city': partner.city,
                'state_id': partner.state_id and partner.state_id.id or False,
                'country_id': partner.country_id and partner.country_id.id or False,
                'email_from': partner.email,
                'phone': partner.phone,
                'mobile': partner.mobile,
                'fax': partner.fax,
                'zip': partner.zip,
                'function': partner.function,
                'user_id': partner.user_id.id
            }
        return {'value': values}

class crm_make_sale(osv.osv_memory):
    """ Make sale  order for crm """

    _inherit = "crm.make.sale"
    #重载转为报价单函数
    def makeOrder(self, cr, uid, ids, context=None):
        """
        This function  create Quotation on given case.
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of crm make sales' ids
        @param context: A standard dictionary for contextual values
        @return: Dictionary value of created sales order.
        """
        # update context: if come from phonecall, default state values can make the quote crash lp:1017353
        context = dict(context or {})
        context.pop('default_state', False)

        case_obj = self.pool.get('crm.lead')
        sale_obj = self.pool.get('sale.order')
        partner_obj = self.pool.get('res.partner')
        data = context and context.get('active_ids', []) or []

        for make in self.browse(cr, uid, ids, context=context):
            partner = make.partner_id
            contacts_id = None
            if partner.parent_id:
                contacts_id = self.pool.get('company.contacts').search(cr, uid, [('contacts_id', '=', partner.id)], context=context)
                if contacts_id:
                    contacts_id = contacts_id[0]
                partner = partner.parent_id
            partner_addr = partner_obj.address_get(cr, uid, [partner.id],
                    ['default', 'invoice', 'delivery', 'contact'])
            pricelist = partner.property_product_pricelist.id
            fpos = partner.property_account_position and partner.property_account_position.id or False
            payment_term = partner.property_payment_term and partner.property_payment_term.id or False
            new_ids = []
            for case in case_obj.browse(cr, uid, data, context=context):
                case.write({'last_contact_date': (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')})
                if case.order_id:
                    raise osv.except_osv(u'错误', u'已经生成过销售报价单')
                if not partner and case.partner_id:
                    partner = case.partner_id
                    fpos = partner.property_account_position and partner.property_account_position.id or False
                    payment_term = partner.property_payment_term and partner.property_payment_term.id or False
                    partner_addr = partner_obj.address_get(cr, uid, [partner.id],
                            ['default', 'invoice', 'delivery', 'contact'])
                    pricelist = partner.property_product_pricelist.id
                if False in partner_addr.values():
                    raise osv.except_osv(_('Insufficient Data!'), _('No address(es) defined for this customer.'))
                #取得商机订单行
                order_line = []
                for lead_line in case.crm_lead_line_ids:
                    line_value = {'product_id': lead_line.product_id.id,
                                  'product_uom_qty': lead_line.product_uom_qty,
                                  'origin_price': lead_line.origin_price,
                                  'price_unit': lead_line.price_unit,
                                  'sale_note': lead_line.sale_note}
                    order_line.append([0, False, line_value])


                vals = {
                    'origin': _('Opportunity: %s') % str(case.id),
                    'section_id': case.section_id and case.section_id.id or False,
                    'categ_ids': [(6, 0, [categ_id.id for categ_id in case.categ_ids])],
                    'partner_id': partner.id,
                    'pricelist_id': pricelist,
                    'partner_invoice_id': partner_addr['invoice'],
                    'partner_shipping_id': partner_addr['delivery'],
                    # 'date_order': fields.datetime.now(),
                    'fiscal_position': fpos,
                    'payment_term':payment_term,
                    'note': sale_obj.get_salenote(cr, uid, [case.id], partner.id, context=context),
                    'order_line': order_line,
                    'contacts_id': contacts_id
                }
                if partner.id:
                    vals['user_id'] = partner.user_id and partner.user_id.id or uid

                new_id = sale_obj.create(cr, uid, vals, context=context)
                sale_order = sale_obj.browse(cr, uid, new_id, context=context)

                contacts_change_result = sale_order.onchange_contacts(contacts_id)
                sale_order.write(contacts_change_result.get('value'))

                case_obj.write(cr, uid, [case.id], {'ref': 'sale.order,%s' % new_id, 'order_id': new_id})
                new_ids.append(new_id)
                message = _("Opportunity has been <b>converted</b> to the quotation <em>%s</em>.") % (sale_order.name)
                case.message_post(body=message)
            if make.close:
                case_obj.case_mark_won(cr, uid, data, context=context)
            if not new_ids:
                return {'type': 'ir.actions.act_window_close'}
            if len(new_ids)<=1:
                value = {
                    'domain': str([('id', 'in', new_ids)]),
                    'view_type': 'form',
                    'view_mode': 'form',
                    'res_model': 'sale.order',
                    'view_id': False,
                    'type': 'ir.actions.act_window',
                    'name' : _('Quotation'),
                    'res_id': new_ids and new_ids[0]
                }
            else:
                value = {
                    'domain': str([('id', 'in', new_ids)]),
                    'view_type': 'form',
                    'view_mode': 'tree,form',
                    'res_model': 'sale.order',
                    'view_id': False,
                    'type': 'ir.actions.act_window',
                    'name' : _('Quotation'),
                    'res_id': new_ids
                }
            return value

# 继承这个修改查找已存在的partner逻辑
class crm_partner_binding(osv.osv_memory):
    _inherit = 'crm.lead2opportunity.partner'

    def _find_matching_partner(self, cr, uid, context=None):
        """
        Try to find a matching partner regarding the active model data, like
        the customer's name, email, phone number, etc.

        :return int partner_id if any, False otherwise
        """
        if context is None:
            context = {}
        partner_id = False
        partner_obj = self.pool.get('res.partner')

        # The active model has to be a lead or a phonecall
        if (context.get('active_model') == 'crm.lead') and context.get('active_id'):
            active_model = self.pool.get('crm.lead').browse(cr, uid, context.get('active_id'), context=context)
        elif (context.get('active_model') == 'crm.phonecall') and context.get('active_id'):
            active_model = self.pool.get('crm.phonecall').browse(cr, uid, context.get('active_id'), context=context)

        # Find the best matching partner for the active model
        if (active_model):
            partner_obj = self.pool.get('res.partner')

            # A partner is set already
            if active_model.partner_id:
                partner_id = active_model.partner_id.id
            # Search through the existing partners based on the lead's email
            # 根据电子邮件搜索
            elif active_model.email_from:
                partner_ids = partner_obj.search(cr, uid, [('email', '=', active_model.email_from)], context=context)
                if partner_ids:
                    partner_id = partner_ids[0]
                    # 如果是联系人的话取得对应的企业客户partner_id
                    partner = partner_obj.browse(cr, uid, partner_id, context=context)
                    if partner.contacts and partner.parent_id:
                        partner_id = partner.parent_id.id
            # 根据手机号码搜索
            elif active_model.mobile:
                partner_ids = partner_obj.search(cr, uid, [('mobile', '=', active_model.mobile)], context=context)
                if partner_ids:
                    partner_id = partner_ids[0]
                    # 如果是联系人的话取得对应的企业客户partner_id
                    partner = partner_obj.browse(cr, uid, partner_id, context=context)
                    if partner.contacts and partner.parent_id:
                        partner_id = partner.parent_id.id

            # Search through the existing partners based on the lead's partner or contact name
            # 根据客户名称搜索
            elif active_model.partner_name:
                partner_ids = partner_obj.search(cr, uid, [('name', 'ilike', active_model.partner_name + '%'), ('customer', '=', True)], context=context)
                if partner_ids:
                    partner_id = partner_ids[0]
            # elif active_model.contact_name:
            #     partner_ids = partner_obj.search(cr, uid, [
            #             ('name', 'ilike', '%'+active_model.contact_name+'%')], context=context)
            #     if partner_ids:
            #         partner_id = partner_ids[0]

        return partner_id

class crm_lead_line(osv.osv):
    _name = 'crm.lead.line'
    def _compute_price_subtotal(self,cr,uid,ids,name,args,context=None):
        res = {}
        for crm_lead_line_row in self.browse(cr,uid,ids,context=context):
            res[crm_lead_line_row.id] = crm_lead_line_row.product_uom_qty*crm_lead_line_row.price_unit
        return res

    def onchange_product_id(self, cr, uid, ids, product_id, context=None):
        if product_id:
            product_row = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
            list_price = product_row.list_price
            return {'value': {'name': product_row.name, 'price_unit': product_row.list_price, 'origin_price': list_price}}

    def create(self, cr, uid, vals,context=None):
        if vals.get('product_uom_qty', 'default_vals') != 'default_vals' and \
                        vals.get('product_uom_qty') <= 0:
            raise osv.except_osv(u'错误', u'产品数量必须大于零')
        return super(crm_lead_line, self).create(cr, uid, vals, context=context)

    def write(self, cr, uid, ids, vals,context=None):
        if vals.get('product_uom_qty', 'default_vals') != 'default_vals' and \
                        vals.get('product_uom_qty') <= 0:
            raise osv.except_osv(u'错误', u'产品数量必须大于零')
        return super(crm_lead_line, self).write(cr, uid, ids, vals, context=context)

    _columns = {
        'crm_lead_id': fields.many2one('crm.lead', u'主线索'),
        'product_id': fields.many2one('product.product', u'产品', domain=[('sale_ok', '=', True),
                                                                         ('active', '=', True)]),
        'name': fields.char(u'描述'),
        'sale_note': fields.char(u'销售备注'),
        'sequence': fields.integer(u'顺序'),
        'product_uom_qty': fields.float(u'数量', digits_compute=dp.get_precision('Product Unit of Measure')),
        'price_unit': fields.float(u'单价'),
        'price_subtotal': fields.function(_compute_price_subtotal, string='小计', store={
        'crm.lead.line': (lambda self, cr, uid, ids, c={}: ids, ['product_uom_qty', 'price_unit'], 10)}),
        'origin_price': fields.float(u'原价'),
    }
    _defaults = {
        'product_uom_qty': 1,
    }
